package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;

public class TestSystem {

	/**
	 * 测试System重定向输出
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		System.out.println("请输入你的名字：");
		String name = cin.nextLine();
		System.out.println("你输入你的年龄");
		int age = cin.nextInt();
		System.out.println("你的名字是：" + name + " " + "你的年龄是：" + age);
		// testOut();
		// testErr();
		// testIn();
	}

	private static void testOut() {
		// 此刻直接输出到屏幕
		System.out.println("hello");
		File file = new File(CharStreamWriteFile.filename);
		try {
			// 测试重定向out
			System.setOut(new PrintStream(new FileOutputStream(file)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("这些内容在文件中才能看到哦！");
	}

	private static void testErr() {
		File file = new File(CharStreamWriteFile.filename);
		System.err.println("这些在控制台输出");
		try {
			System.setErr(new PrintStream(new FileOutputStream(file)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.err.println("这些在文件中才能看到哦！");
	}

	private static void testIn() {
		File file = new File(CharStreamWriteFile.filename);
		if (!file.exists()) {
			return;
		} else {
			try {
				System.setIn(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			byte[] bytes = new byte[1024];
			int len = 0;
			try {
				len = System.in.read(bytes);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("读入的内容为：" + new String(bytes, 0, len));
		}
	}
}
